//
//  HHInputPropretyViewController.m
//  HHBroker
//
//  Created by He Wei on 9/18/15.
//  Copyright © 2015 harry. All rights reserved.
//

#import "HHInputPropertyViewController.h"
#import "HHPropertyInfoModel.h"
#import "HHPropertyTableViewCell.h"
#import "HHLineView.h"
#import "HttpRequestManager.h"
#import "NSString+ValidateArgument.h"
#import "JiaYuanShareData.h"
#import "HHApplyServiceViewController.h"


@interface HHInputPropertyViewController () <UITableViewDataSource, UITableViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource,UIScrollViewDelegate, HHPropertyTableViewCellDelegate>

@property (nonatomic, strong) UIView *indicateView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIBarButtonItem *leftItem;
@property (nonatomic, strong) UIButton *signinButton;
@property (nonatomic, strong) NSMutableArray *dataArray;

/**
 *  省份数组
 *  数组中每个元素是字典 eg.@{@"code":11,@"value":@"北京"}
 */
@property (nonatomic, strong) NSMutableArray *proviceArray;
/*
 *  城市数组
 *  数组中每个元素是当前选中省份对应的城市数组
 *  这个城市数组中的每个元素是字典 e.g. @{@"code":1101, @"value":@"朝阳区"}
 */
@property (nonatomic, strong) NSMutableArray *citiesArray;
@property (nonatomic, assign) NSInteger selectedProvince;
@property (nonatomic, assign) NSInteger selectedCity;

/*
 *  键盘高度
 */
@property (nonatomic, assign) NSInteger keyboardHeight;
@end

@implementation HHInputPropertyViewController
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"注册";
    [self.view addSubview:self.indicateView];
    [self.view addSubview:self.tableView];
    self.navigationItem.leftBarButtonItem = self.leftItem;
    [self prepareData];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //self.view.backgroundColor = [UIColor redColor];
}

#pragma mark -
#pragma mark - Delegate

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseCell = @"reuseCell";
    HHPropertyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseCell];
    if (cell == nil) {

        cell = [[[NSBundle mainBundle] loadNibNamed:@"HHPropertyTableViewCell" owner:self options:nil] lastObject];
    }
    cell.isFirst = NO;
    cell.isLast = NO;
    if (indexPath.row == 0) {
        cell.isFirst = YES;
    }
    if (indexPath.row == self.dataArray.count-1) {
        cell.isLast = YES;
    }
    HHPropertyInfoModel *model = self.dataArray[indexPath.row];
    cell.indexPath = indexPath;
    cell.delegate = self;
    cell.model = model;
    if (model.inputType == 1) {
        UIPickerView *pickView = [[UIPickerView alloc] initWithFrame: CGRectMake(0, 0, self.view.size.width, 216)];
        pickView.delegate = self;
        pickView.dataSource = self;
        pickView.backgroundColor = [UIColor whiteColor];
        pickView.showsSelectionIndicator = YES;
        cell.infoTextField.inputView = pickView;
        self.selectedProvince = 0;
        self.selectedCity = 0;
        [pickView selectRow:0 inComponent:0 animated:YES];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0000001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HHPropertyTableViewCell *cell = (HHPropertyTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell.infoTextField becomeFirstResponder];

}

#pragma mark -HHPropertyTableViewCellDelegate
- (void)HHPropertyTableViewCell:(HHPropertyTableViewCell *)cell didBeginEditingWithIndexPath:(NSIndexPath *)indexPath type:(NSInteger)type tag:(NSInteger)tag
{
    NSInteger originY = cell.frame.origin.y;
    NSInteger visibleHeight = kCurrentHeight-64-44-self.keyboardHeight;
    if (originY+44 > visibleHeight) {
        NSInteger wantOffset = originY+44-visibleHeight;
        [self.tableView setContentOffset:CGPointMake(self.tableView.contentOffset.x, wantOffset) animated:YES];
    }
    if (type == 1) {
        if (cell.infoTextField.text.length == 0) {
            cell.infoTextField.text = @"上海 闵行";
        }
    }
}

- (void)HHPropertyTableViewCell:(HHPropertyTableViewCell *)cell selectNextResponseWithIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= 0 && indexPath.row < self.dataArray.count-1) {
        HHPropertyTableViewCell *nextCell = (HHPropertyTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]];
        NSInteger originY = nextCell.frame.origin.y;
        NSInteger visibleHeight = kCurrentHeight-64-44-self.keyboardHeight;
        
        if (originY+44 > visibleHeight) {
            NSInteger wantOffset = originY+44-visibleHeight;
            [self.tableView setContentOffset:CGPointMake(self.tableView.contentOffset.x, wantOffset) animated:YES];
        }
        [nextCell.infoTextField becomeFirstResponder];
    }

}

- (void)HHPropertyTableViewCell:(HHPropertyTableViewCell *)cell selectLastResponseWithIndexPath:(NSIndexPath *)indexPath
{
    HHPropertyTableViewCell *lastCell = (HHPropertyTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1   inSection:0]];
    NSInteger originY = lastCell.frame.origin.y;
    NSInteger visibleHeight = kCurrentHeight-64-44-self.keyboardHeight;
    
    if (originY-self.tableView.contentOffset.y+44 < visibleHeight) {
        if (self.tableView.contentOffset.y <= 0 || indexPath.row-1 == 0) {
            [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        } else {
            NSInteger wantOffset = visibleHeight-(originY-self.tableView.contentOffset.y+44);
            [UIView animateWithDuration:0.25 animations:^{
                self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y-wantOffset);
            }];
        
        }
    }
    [lastCell.infoTextField becomeFirstResponder];
}

- (void)HHPropertyTableViewCell:(HHPropertyTableViewCell *)cell completeResponseWithIndexPath:(NSIndexPath *)indexPath
{
    HHPropertyInfoModel *model = self.dataArray[indexPath.row];
    model.value = cell.infoTextField.text;
    [self.view endEditing:YES];
    if (!self.tableView.isTracking) {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }

}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.tracking) {
        [self.view endEditing:YES];
    }

}

#pragma mark - UIPickerViewDataSource
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return [self.proviceArray count];
    } else {
        return [[self.citiesArray objectAtIndex:self.selectedProvince] count];
    }

}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;

}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return self.proviceArray[row][@"value"];
    } else {
    
        return self.citiesArray[self.selectedProvince][row][@"value"];
    }

}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.selectedProvince = row;
        self.selectedCity = 0;
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
    } else if (component == 1) {
        self.selectedCity = row;
    }
    NSString *proviceName = self.proviceArray[self.selectedProvince][@"value"];
    NSString *cityName = self.citiesArray[self.selectedProvince][self.selectedCity][@"value"];
    HHPropertyTableViewCell *cell = (HHPropertyTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    cell.infoTextField.text = [NSString stringWithFormat:@"%@ %@", proviceName, cityName];

}

#pragma mark -Event Response
- (void)signinButtonClicked:(UIButton *)button
{
    [self.view endEditing:YES];
    
    NSString *userName = [(HHPropertyInfoModel *)self.dataArray[0] value];
    NSString *password = [(HHPropertyInfoModel *)self.dataArray[1] value];
    NSString *realName = [(HHPropertyInfoModel *)self.dataArray[2] value];
    NSString *identityNumber = [(HHPropertyInfoModel *)self.dataArray[3] value];
    NSString *liveLocation = [(HHPropertyInfoModel *)self.dataArray[5] value];
    NSString *cityId = self.citiesArray[self.selectedProvince][self.selectedCity][@"code"];
    //验证数据
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    if (![NSString validateUserName:userName]) {
        if (userName.length == 0) {
            alertView.title = @"用户名不能为空";
        } else {
            alertView.title = @"用户名必须为6位以上英文或数字";
        }
        [alertView show];
        return;
    }
    if (![NSString validatePassword:password]) {
        if (password.length == 0) {
            alertView.title = @"密码不能为空";
        } else {
            alertView.title = @"密码必须8位以上";
        }
        [alertView show];
        return;
    }
    if (!realName || realName.length == 0) {
        alertView.title = @"姓名不能为空";
        [alertView show];
        return;
    }
    if (![NSString validateIdentityNumber:identityNumber]) {
        if (identityNumber.length == 0) {
            alertView.title = @"身份证号不能为空";
        } else {
            alertView.title = @"身份证号有误";
        }
        [alertView show];
        return;
    }
    
    if (!liveLocation || liveLocation.length == 0) {
        alertView.title = @"常驻地址不能为空";
        [alertView show];
        return;
    }
    if (![NSString validateMobile:self.phone]) {
        alertView.title = @"注册手机号有误";
        [alertView show];
        return;
    }
    
    // 参数mobile, emp_name(用户名), password（密码）, emp_ranme（真实姓名）,idcard（身份证）, emp_city（省市中的市）, address（详细地址)
    realName = [realName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    liveLocation = [liveLocation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = @{@"action":@"signup",
                          @"mobile":self.phone,
                          @"emp_name":userName,
                          //@"password":[JiaYuanEncrypt AES128Encrypt:password key:kSecuCode],
                          @"emp_rname":realName,
                          @"idcard":identityNumber,
                          @"emp_city":cityId,
                          @"address":liveLocation};
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.mode = MBProgressHUDModeIndeterminate;
  //    跳转   ＊/
    HHApplyServiceViewController *apply = [[HHApplyServiceViewController alloc] init];
    apply.title = @"注册成功";
    [self.navigationController pushViewController:apply animated:YES];

    return;

    [HttpRequestManager postWithUrlString:KUrlNewRegister parameters:dic success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        hub.mode = MBProgressHUDModeText;
        if (code == 1) {
            JiaYuanShareData *shareData = [JiaYuanShareData sharedInstance];
            NSDictionary *data = [response objectForKey:@"record"];
            if (data) {
                // uid token
                // TODO: 该过程包含登录 验证码登录 注册流程 封装起来
                NSString *token = [response objectForKey:@"token"];
                NSString *uid = [data objectForKey:@"emp_id"];
                shareData.uid = uid;
                shareData.token = token;
                shareData.shopId = [data objectForKey:@"shop_id"];
                shareData.emp_rname = [data objectForKey:@"emp_rname"];
                shareData.emp_name = [data objectForKey:@"emp_name"];
                shareData.emp_city = [data objectForKey:@"emp_city"];
                shareData.address = [data objectForKey:@"address"];
                shareData.idCard = [data objectForKey:@"emp_idcard"];
                
            }
            hub.labelText = [response objectForKey:@"msg"];
            hub.completionBlock = ^ {
                HHApplyServiceViewController *apply = [[HHApplyServiceViewController alloc] init];
                apply.title = @"注册成功";
                [self.navigationController pushViewController:apply animated:YES];
            };
        } else {
            if (code == -1) {
            }
            hub.labelText = [response objectForKey:@"msg"];
        }
        [hub hide:YES afterDelay:1];
        
    } failure:^(NSError *error) {
        hub.mode = MBProgressHUDModeText;
        hub.labelText = @"网络有点问题!";
        [hub hide:YES afterDelay:2];
    } isLogin:NO];

}


- (void)keyboardWillShow:(NSNotification *)note{
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
    if (keyboardBounds.size.height > 260) {
        self.keyboardHeight = keyboardBounds.size.height;
    }

}

- (void)leftItemClicked:(UIButton *)button
{
    [self.navigationController popToRootViewControllerAnimated:YES];

}

#pragma mark - Setter && Gettet
- (UIView *)indicateView
{
    if (_indicateView == nil) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width,44)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        textLabel.textAlignment = NSTextAlignmentCenter;
        textLabel.font = kJiaYuanFontWithSize(14.0f);
        textLabel.textColor = UIColorFromRGB(0x3b3b3b);
        NSString *string = @"1.输入手机号 > 2.输入验证码 > 3.填写资料";
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
        NSRange range = [string rangeOfString:@"3.填写资料"];
        [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff6a6a) range:range];
        textLabel.attributedText = str;
        [view addSubview:textLabel];
        
        HHLineView *lineView = [HHLineView lineViewWithY:43];
        [view addSubview:lineView];
        _indicateView = view;
        
    }
    return _indicateView;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64+44, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        
        tableView.tableFooterView = self.footerView;
        _tableView = tableView;
    }
    return _tableView;
}
- (UIView *)footerView
{
    if (_footerView == nil) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kCurrentWidth, 64)];
        _footerView.backgroundColor = [UIColor clearColor];
        [_footerView addSubview:self.signinButton];
    }
    return _footerView;
}

- (UIButton *)signinButton
{
    if (_signinButton == nil) {
        UIButton *subButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [subButton setTitle:@"注册" forState:UIControlStateNormal];
        subButton.titleLabel.font = kJiaYuanFontWithSize(18.0f);
        [subButton setBackgroundImage:[UIImage imageNamed:@"button_denglu_normal"] forState:UIControlStateNormal];
        [subButton setBackgroundImage:[UIImage imageNamed:@
                                       "button_denglu_press"] forState:UIControlStateHighlighted];
        subButton.frame = CGRectMake(15, 10, _footerView.width-(15*2), 44);
        [subButton addTarget:self action:@selector(signinButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        _signinButton = subButton;
    }
    return _signinButton;
}

- (UIBarButtonItem *)leftItem
{
    if (_leftItem == nil) {
        
   
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 44, 44);
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(leftItemClicked:) forControlEvents:UIControlEventTouchUpInside];
    _leftItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
    return _leftItem;
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] initWithCapacity:6];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"HHPropertyList" ofType:@"plist"];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        for (NSDictionary *dictionary in array) {
            HHPropertyInfoModel *model = [[HHPropertyInfoModel alloc] init];
            [model setValuesForKeysWithDictionary:dictionary];
            [_dataArray addObject:model];

        }
    }
    return _dataArray;
   // NSLog(@"%lu", _dataArray.count);

}


- (void)prepareData
{
    self.keyboardHeight = 297;
    self.proviceArray = [[NSMutableArray alloc] init];
    self.citiesArray = [[NSMutableArray alloc] init];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"HHCityList" ofType:@"plist"];
    NSDictionary *diction = [NSDictionary dictionaryWithContentsOfFile:path];
    NSDictionary *proviceDic = [diction objectForKey:@"100"];
    NSDictionary *cityDic = [diction objectForKey:@"101"];
    
    NSArray *array = [[proviceDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    @autoreleasepool {
        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        for (NSString *key in array) {
            NSString *value = [proviceDic objectForKey:key];
            NSDictionary *dic = @{@"code":key, @"value":value};
            [tempArray addObject:dic];
        }
        [self.proviceArray addObjectsFromArray:tempArray];
    }
    @autoreleasepool {
        for (NSString *key in array) {
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            NSArray *cityKeys = [[cityDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
            for (NSString *cityKey in cityKeys) {
                if ([[cityKey substringToIndex:2] isEqualToString:key]) {
                    NSString *value = [cityDic objectForKey:cityKey];
                    NSDictionary *dic = @{@"code":cityKey, @"value":value};
                    [tempArray addObject:dic];
                }
                if ([[cityKey substringToIndex:2] integerValue] > [key integerValue]) {
                    break;
                }
            }
            [self.citiesArray addObject:tempArray];
        }
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
